package com.jn.gsondemo.views;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import com.jn.gsondemo.R;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BookDetailActivity extends Activity {
    private TextView titleTextView;
    private TextView authorTextView;
    private TextView descriptionTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_detail);

        // 初始化UI元素
        titleTextView = findViewById(R.id.titleTextView);
        authorTextView = findViewById(R.id.authorTextView);
        descriptionTextView = findViewById(R.id.descriptionTextView);

        // 解析JSON数据
        parseJson();
    }

    private void parseJson() {
        // 读取assets文件夹中的book.json文件
        String json = readJsonFromAsset("book.json");
        try {
            JSONObject bookObject = new JSONObject(json);
            String title = bookObject.getString("title");
            String author = bookObject.getString("author");
            String description = bookObject.getString("description");

            // 将数据设置到UI元素上
            titleTextView.setText(title);
            authorTextView.setText(author);
            descriptionTextView.setText(description);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String readJsonFromAsset(String fileName) {
        StringBuilder builder = new StringBuilder();
        try {
            InputStream is = getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
}